﻿using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Batman.Core;
using Batman.Core.Utilities;
using Batman.IdentityServer.Weixin.Consts;
using IdentityModel;

namespace Batman.IdentityServer.Weixin
{
    public static class ClientExtension
    {
        public static async Task<ResponseBase<WeixinOpenTokenResponse>> RequestWeixinOpenTokenAsync(this HttpClient client, WeixinOpenTokenRequest request)
        {
            try
            {
                if (string.IsNullOrEmpty(request.Scope) ||
                    !request.Scope.Contains("IdentityServerApi"))
                {
                    request.Scope += " IdentityServerApi";
                }

                var parameters = new List<KeyValuePair<string, string>>
                {

                    new KeyValuePair<string, string>(OidcConstants.TokenRequest.GrantType, GrantTypeConstants.WeixinOpen),
                    new KeyValuePair<string, string>(OidcConstants.TokenRequest.ClientId, request.ClientId),
                    new KeyValuePair<string, string>(OidcConstants.TokenRequest.ClientSecret, request.ClientSecret),
                    new KeyValuePair<string, string>(OidcConstants.TokenRequest.Scope, request.Scope),
                    new KeyValuePair<string, string>(ParamConstants.OpenId, request.OpenId),
                    new KeyValuePair<string, string>(ParamConstants.UnionId, request.UnionId),
                };


                var response = await client.PostAsync(request.Address, new FormUrlEncodedContent(parameters));

                var responseContent = await response.Content.ReadAsStringAsync();
                return new ResponseBase<WeixinOpenTokenResponse>
                {
                    Result = JsonUtil.Parse<WeixinOpenTokenResponse>(responseContent)
                };
            }
            catch (Exception ex)
            {
                return new ResponseBase<WeixinOpenTokenResponse>(false, ex.Message);
            }
        }
    }
}
